package TreePractice;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;

class Tree extends JFrame implements TreeSelectionListener{
    JTree tree;
    JTextArea textArea;
    public Tree(){
        DefaultMutableTreeNode root=new DefaultMutableTreeNode("商品");
        DefaultMutableTreeNode nodeTV=new DefaultMutableTreeNode("电视");
        DefaultMutableTreeNode nodePhone=new DefaultMutableTreeNode("手机");
        DefaultMutableTreeNode TV1=new DefaultMutableTreeNode(new Goods("长虹电视",3452));
        DefaultMutableTreeNode TV2=new DefaultMutableTreeNode(new Goods("Sony电视",6788));
        DefaultMutableTreeNode TV3=new DefaultMutableTreeNode(new Goods("海信电视",5467));
        DefaultMutableTreeNode Phone1=new DefaultMutableTreeNode(new Goods("诺基亚",3000));
        DefaultMutableTreeNode Phone2=new DefaultMutableTreeNode(new Goods("小米",4000));
        DefaultMutableTreeNode Phone3=new DefaultMutableTreeNode(new Goods("华为",4200));
        DefaultMutableTreeNode Phone4=new DefaultMutableTreeNode(new Goods("苹果",6700));
        root.add(nodeTV);
        root.add(nodePhone);
        nodeTV.add(TV1);
        nodeTV.add(TV2);
        nodeTV.add(TV3);
        nodePhone.add(Phone1);
        nodePhone.add(Phone2);
        nodePhone.add(Phone3);
        nodePhone.add(Phone4);
        tree=new JTree(root);
        tree.addTreeSelectionListener(this);
        textArea=new JTextArea();
        setLayout(new GridLayout(1,2));
        add(new JScrollPane(tree));
        add(new JScrollPane(textArea));
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    @Override
    public void valueChanged(TreeSelectionEvent e) {
        DefaultMutableTreeNode node= (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (node.isLeaf()){
            Goods s= (Goods) node.getUserObject();//获取节点中对象
            textArea.append(s.name+" "+s.price+"元\n");
        }else {
            textArea.setText(null);

        }

    }


}
class  Goods{
    String name;
    double price;

    public Goods(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}
public class TreeExam {
    public static void main(String[] args) {
        Tree tree = new Tree();
        tree.setBounds(200,200,500,400);
        tree.setTitle("树的练习");

    }
}
